<?php


namespace app\common\model;


use think\Db;
use think\Model;

class UserIncome extends Model
{
    // 表名
    protected $name = 'user_income';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];

    /**
     * 变更会员余额
     * @param int    $money   余额
     * @param int    $user_id 会员ID
     * @param string $memo    备注
     */
    public static function money($money, $user_id, $memo)
    {
        Db::startTrans();
        try {
            $user =  self::lock()->where(['user_id' => $user_id])->find();
            if ($user && $money != 0) {
                $after = function_exists('bcadd') ? bcadd($user->money, $money, 2) : $user->money + $money;;
                //写入日志
                UserIncomeLog::create(['user_id' => $user_id, 'money' => $money, 'msg' => $memo]);
                if($money > 0) {
                    $share_money = $user->share_money;
                    $user->share_money = $share_money + $money;
                }
                //更新会员信息
                $user->money = $after;
                $user->save();
                User::money($money,$user_id,$memo);
            }
            Db::commit();
        } catch (\Exception $e) {
            var_dump($e->getMessage());die;
            Db::rollback();
        }
    }

    public function user()
    {
        return $this->belongsTo("User", 'user_id', 'id')->setEagerlyType(0);
    }
}